package org.lhg.activiti.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.lhg.activiti.mapper.LeaveMapper;
import org.lhg.activiti.model.StudentLeave;
import org.lhg.activiti.service.LeaveService;
import org.lhg.activiti.util.ElUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class LeaveServiceImpl extends ServiceImpl<LeaveMapper, StudentLeave> implements LeaveService {
    @Autowired
    private LeaveMapper leaveMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Value("${leaveApply}")
    private String leaveApply;

    @Override
    public int addLeave(StudentLeave leave) {
        //工作流
        Map<String,Object> variables=new HashMap<String,Object>();
        variables.put("url","/leave/finshApply");
        //流程变量(网关)
        variables.put("days",leave.getLeaveDays());
        // 启动流程
        ProcessInstance pi= runtimeService.startProcessInstanceByKey(leaveApply,variables);
        // 根据流程实例Id查询任务
        Task task=taskService.createTaskQuery().processInstanceId(pi.getProcessInstanceId()).singleResult();
        taskService.setAssignee(task.getId(),leave.getUserId());
        // 完成任务
        taskService.complete(task.getId());

        // 根据流程实例Id查询任务
        Task taskNext=taskService.createTaskQuery().processInstanceId(pi.getProcessInstanceId()).singleResult();
        if(ElUtils.isNotBlank(leave.getReview_user())){
            //设置下一审批人
            taskService.setAssignee(taskNext.getId(),leave.getReview_user());
        }

        leave.setProcessInstanceId(pi.getProcessInstanceId());
        leave.setProcessInstanceKey(leaveApply);

        return leaveMapper.addLeave(leave);
    }

    @Override
    public List<StudentLeave> listLeave(Map<String, Object> map) {
        return leaveMapper.listLeave(map);
    }

    @Override
    public Long getTotal(Map<String, Object> map) {
        return leaveMapper.getTotal(map);
    }

    @Override
    public StudentLeave findById(Integer leaveId) {
        return leaveMapper.findById(leaveId);
    }

    @Override
    public int update(StudentLeave leave) {
        return leaveMapper.update(leave);
    }

    @Override
    public StudentLeave leave_by_processInstanceId(String processInstanceId) {
        return leaveMapper.leave_by_processInstanceId(processInstanceId);
    }
}
